package com.news.service.impl;

import com.news.dao.UserDao;
import com.news.model.User;
import com.news.service.UserService;
import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDao();
    
    @Override
    public User login(String username, String password) {
        return userDao.login(username, password);
    }
    
    @Override
    public boolean addUser(User user) {
        return userDao.addUser(user);
    }
    
    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }
    
    @Override
    public boolean deleteUser(Integer userId) {
        return userDao.deleteUser(userId);
    }
    
    @Override
    public User findById(Integer userId) {
        return userDao.findById(userId);
    }
    
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
    
    @Override
    public boolean isUsernameExists(String username) {
        return userDao.isUsernameExists(username);
    }
    
    @Override
    public boolean isEmailExists(String email) {
        return userDao.isEmailExists(email);
    }
    
    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }
    
    @Override
    public String register(User user) {
        // 检查用户名是否已存在
        if (isUsernameExists(user.getUsername())) {
            return "用户名已存在";
        }
        
        // 检查邮箱是否已存在
        if (isEmailExists(user.getEmail())) {
            return "邮箱已被使用";
        }
        
        // 设置为普通用户
        user.setAdmin("user");
        
        // 添加用户
        if (addUser(user)) {
            return null;  // 注册成功返回null
        } else {
            return "注册失败，请稍后重试";
        }
    }
    
    @Override
    public String resetPassword(String username, String newPassword) {
        User user = findByUsername(username);
        if (user == null) {
            return "用户不存在";
        }
        
        user.setPassword(newPassword);
        if (updateUser(user)) {
            return null;  // 重置成功返回null
        } else {
            return "密码重置失败，请稍后重试";
        }
    }
    
    @Override
    public int getUserCount(String keyword) {
        return userDao.getUserCount(keyword);
    }
    
    @Override
    public List<User> getUsersByPage(int page, int pageSize, String keyword) {
        int offset = (page - 1) * pageSize;
        return userDao.getUsersByPage(offset, pageSize, keyword);
    }
    
    @Override
    public boolean deleteUser(int userId) {
        return userDao.deleteUser(userId);
    }
} 